<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Links;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class LinksController extends CommonController
{

    //get  admin/links   全部分类列表
    public function index(){
        $data = Links::orderBy('link_order','asc')->get();
        return view('admin.links.index',compact('data'));
    }



    //post  admin/links  获取要添加的数据并存储到数据库
    public function store(){
        //验证
        $input = Input::except('_token');
        $rules = [
            'link_name'=>'required',//定义规则，规则都是框架自带的
            'link_url'=>'required'
        ];
        //提示信息
        $message = [
            'link_name.required'=>'链接名称不能为空',
            'link_url.required'=>'链接url不能为空'
        ];
        //创建验证对象，哪些post值，规则是什么，提示什么

        $validator = Validator::make($input,$rules,$message);
        //如果通过验证，
        if($validator->passes()){

            $re = Links::create($input);
            if($re){
                return redirect('admin/links');
            }else{
                return back()->with('errors','数据填入失败');
            }


        }else{

            return back()->withErrors($validator);
        }

    }

    //get. admin/links/create   添加页面的显示及数据分配
    public function create(){
        
        return view('admin.links.add');
    }

    //get admin/category/{category}
    public function show(){

    }

    //delete admin/links/{link_id} 删除链接
    public function destroy($link_id){
        $re = Links::where('link_id',$link_id)->delete();
        if($re){
           $data = [
               'status'=>1,
               'msg'=>'友情链接删除成功'
           ];
        }else{
            $data = [
                'status'=>0,
                'msg'=>'友情链接删除失败'
            ];
        }

        return $data;
    }

    //put admin/links/{links}   更新友情链接
    public function update($link_id){
        $input = Input::except('_token','_method');
        $re = Links::where('link_id',$link_id)->update($input);
        if($re){
            return redirect('admin/links');
        }else{
            return back()->with('errors','数据更新失败');
        }
    }

    //get admin/links/{links}/edit   显示编辑模版及分配数据
    public function edit($link_id){
        $link_data = Links::find($link_id);
        return view('admin.links.edit',compact('link_data'));
    }

    //异步排序
    public function change_order(){

        $input = Input::all();

        $link_order = $input['link_order'];
        $link_data = Links::find($input['link_id']);
        $link_data->link_order = $link_order;
        $re = $link_data->update();
        if($re){
            $data=[
                'status'=>'1',
                'msg'=>"排序修改成功"
            ];
        }else{
            $data=[
                'status'=>'0',
                'msg'=>"排序修改失败"
            ];
        }

        return $data;
    }

}
